from db import db
from fvutil.managers import objectmanager
from fvutil import fvcon
from util import config
from presence import ps

import gobject
import random
import os

def get_audio_duration(path):
    return os.path.getsize(path) / 16000 * 1000 # 1 channel, 16 bts, 8000 times a second in MS

class AudioPresence(ps.ObjectPresence):

    def __init__(self, oid, name):
        ps.ObjectPresence.__init__(self, oid, name)
    
    
class AudioManager(objectmanager.ObjectManager):
    
    __gsignals__ = {
            'sent_audio' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                    (gobject.TYPE_INT, gobject.TYPE_INT,)),
            'received_audio' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                    (gobject.TYPE_PYOBJECT,)),
    }
    
    LENGTH = 14001
    
    def __init__(self, async, my_id, mixer):
        objectmanager.ObjectManager.__init__(self, fvcon.AUDIO, my_id)
        self.__async = async
        self.__path = config.get('async.folders', fvcon.AUDIO)
        
        print 'AudioManager: Path - ',self.__path
        self.__temp_rec_file_name = self.__path+"temp_audio.wav"
        for detail in self.get_all():
            print 'Adding input for',detail
            mixer.onAddInput(self, detail)
        
    def send(self, data):
        tags = data['tags']
        dests = data['recipients']
        meta = {
                AudioManager.LENGTH: get_audio_duration(self.__temp_rec_file_name),
                fvcon.TAGS: tags
                }
        
        id = random.randint(1,100000)
        newpath = self.__path + '/' +  str(id) + '.audio'
        os.rename(self.__temp_rec_file_name, newpath)
        header = self.__async.send_message(newpath, fvcon.AUDIO, dests, meta)
        self.add(header)
        print 'Added audio:',header.mid
        self.emit('sent_audio', header.mid, fvcon.AUDIO)
        
    def receive(self, header):
        self.add(header)
        flash = self.to_flash(header)
        self.emit('received_audio', flash)
        
    def to_flash(self, header):
        return {'type':fvcon.AUDIO, 
                'subcommand':fvcon.ADD, 
                'id':header.mid, 
                'label':header.meta[fvcon.TAGS],
                'tags':header.meta[fvcon.TAGS],
                'date':header.created,
                'authorID':header.src,
                'src':header.src,
                'local_path':header.get_file_path(),
            	'status': fvcon.ONLINE,
                }